package consumer

import (
	"context"
	"encoding/json"
	"gitee.com/zylvcxq/gotham-utils/log_util"
	"gitee.com/zylvcxq/gotham-utils/mail"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/tx7do/kratos-transport/broker"
	"gotham-plan-manage/internal/app/convertor"
	"gotham-plan-manage/internal/app/daily_user_handler"
	"gotham-plan-manage/internal/infra/cache/redis"
)

/*
   @author:zhongyang
   @date:2023/8/2
   @description:计划管理服务消费者
*/

type PlanManageConsumer struct {
	convertor    convertor.PlanManageConvertor
	EntryHandler daily_user_handler.Handler
	logger       *log_util.GothamLogger
}

func NewPlanManageConsumer(entryHandler daily_user_handler.Handler, logger log.Logger) *PlanManageConsumer {
	return &PlanManageConsumer{EntryHandler: entryHandler, logger: log_util.NewGothamLogger(logger, mail.NewRealMailSender(redis.GetConn()))}
}

// HandleUserDaily 这里处理程序是一条条处理，后续改成goroutine的形式，让他并发执行，更加符合用户行为。
func (p *PlanManageConsumer) HandleUserDaily(ctx context.Context, event broker.Event) error {
	p.logger.Infof(ctx, "开始执行，msg:%+v", event.Message())
	go func() {
		defer func() {
			if err := recover(); err != nil {
				p.logger.Errorf(ctx, "PlanManageConsumer.handleUserDaily#1 err:%v", err)
			}
		}()
		err := p.handleUserDaily(ctx, event)
		if err != nil {
			p.logger.Errorf(ctx, "PlanManageConsumer.handleUserDaily#2 err:%v", err)
		}
	}()
	return nil
}

func (p *PlanManageConsumer) handleUserDaily(ctx context.Context, event broker.Event) error {
	user, _ := json.Marshal(event.Message().Body)
	userMap := make(map[string]interface{})
	err := json.Unmarshal(user, &userMap)
	if err != nil {
		p.logger.Errorf(ctx, "PlanManageConsumer.HandleUserDaily Unmarshal err:%v", err)
		return err
	}
	if userId, ok := userMap["userId"]; ok {
		ctx = context.WithValue(ctx, "user_id", userId.(string))
	} else {
		p.logger.Errorf(ctx, "PlanManageConsumer.HandleUserDaily userId格式异常")
		return nil
	}

	if account, ok := userMap["account"]; ok {
		ctx = context.WithValue(ctx, "account", account.(string))
	} else {
		p.logger.Errorf(ctx, "PlanManageConsumer.HandleUserDaily account格式异常")
		return nil
	}

	err = p.EntryHandler.Handle(ctx)
	if err != nil {
		p.logger.Errorf(ctx, "PlanManageConsumer.HandleUserDaily userId:%s消息异常 err:%v", userMap["userId"], err)
		return err
	}
	return nil
}
